<?php
class DBAdapterException extends Exception {}
class DBAdapterConnectFail extends DBAdapterException {}
class DBAdapterQueryFail extends DBAdapterException {}

class DBAdapter {
  
  public static $link;
  protected $mLoginInfo = NULL;
  
  const ASSOC          = 1;
  const AFFECTED_ROWS  = 2;
  const LAST_INSERT_ID = 3;
  const NONE           = 4;
  
  /**
   *  Meant to be initialized by autoloader
   */ 
  public static function init() {
    self::ConnectToDB();
  }

  
  public static function ConnectToDB(Array $pConnectionConf = NULL)
  {
    if ( !is_null($pConnectionConf) ) {
      $host    = $pConnectionConf['host'];
      $db_name = $pConnectionConf['db_name'];
      $user    = $pConnectionConf['user'];
      $pass    = $pConnectionConf['pass'];
      self::$mLoginInfo = $pConnectionConf;
    }
     else {
       $host    = Conf::get('DB_HOST');
       $db_name = Conf::get('DB_NAME');
       $user    = Conf::get('DB_USER');
       $pass    = Conf::get('DB_PASS');
     }
    self::$link = @ new mysqli( $host, $user, $pass, $db_name );
    
    
    if ( mysqli_connect_errno() ) {
      $errNo  = mysqli_connect_error();
      $errMsg = mysqli_connect_error();
      throw new DBAdapterConnectFail( "Failed to connect to the database: " . $errMsg . "(".$errNo.")" , 0 );
    }
    return TRUE;    
  }
  
  
  public static function queryAssoc($sql) {
    return self::query($sql, self::ASSOC);
  }
  
  public static function queryAffectedRows($sql) {
    return self::query($sql, self::AFFECTED_ROWS);
  }
  
  public static function queryLastInsertId($sql) {
     return self::query($sql, self::LAST_INSERT_ID);
  }
  
  
  public static function query( $pSQL, $pPostPrParam = NULL ) {
    $result = self::getQueryResult($pSQL);
    
    switch( $pPostPrParam )
    {
      case self::AFFECTED_ROWS :
                    return  self::$link->affected_rows;
           break;
           
      case self::LAST_INSERT_ID:
                    return self::$link->insert_id;
          break;     
      
          
      case self::NONE:  break;
          
      case self::ASSOC :      
      default:
                while ( $row = $result->fetch_assoc() ) {
                      $rows[] = $row;
                    }
                    return $rows;
           break;  
    } 
  }
  
  
  public static function getQueryResult( $pSQL ) {
    if ( !( self::$link instanceof mysqli ) ) {
      //attempt to reconnect if disconected (latest login info array is used):
      $this->ConnectToCurrentDB(self::$mLoginInfo);
    }
    
    $result = self::$link->query( $pSQL );
    if ( !$result ) {
      echo $pSQL;
      throw new DBAdapterQueryFail(  $pSQL . ' : '.self::$link->error . '('.self::$link->errno.')' , 1 );
    }
    return $result;
  }
  
}

?>